import logging
import os
from flask import Blueprint, jsonify, request
from app.utils.aoi_utils import read_file_with_multiple_encodings, detect_aoi_file_type, unify_aoi_data
from mysql_tool.mysql_tool import MySQLTool
from app.config.paths import SMT1_AOI_PATH

smt1_aoi_bp = Blueprint('smt1_aoi', __name__)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 定义SMT1 AOI数据文件的Linux路径
# SMT1_AOI_PATH = "/mnt/smt1/aoi/ShopFloor"


def get_smt_npm_scan_record(serial_number):
    """查询锡膏信息（根据流水号获取同批次所有流水号）"""
    logger.info(f"查询流水号批次信息: {serial_number}")

    # 创建数据库连接
    mysql_tool = MySQLTool()

    # 使用参数化查询防止SQL注入
    smt_sql = """
              SELECT batch_code, \
                     serial_number
              FROM smt_npm_scan_record
              WHERE batch_code = (SELECT a.batch_code FROM smt_npm_scan_record AS a WHERE a.serial_number = %s  LIMIT 1) \
              """

    logger.info(f"执行SQL: {smt_sql}, 参数: {serial_number}")
    results = mysql_tool.execute_query(smt_sql, (serial_number,))

    smt_data = []
    for row in results:
        item = {
            "batchCode": row[0],
            "serialNumber": row[1],
        }
        smt_data.append(item)

    logger.info(f"找到同批次流水号: {len(smt_data)}个")
    return smt_data


@smt1_aoi_bp.route('/api/smt1aoi/query/<serial_number>', methods=['GET'])
def query_smt1_aoi_data(serial_number):
    """SMT1 AOI数据查询接口，通过流水号查询对应的PARMI设备AOI测试数据"""
    try:
        if not serial_number:
            return jsonify({"success": False, "message": "流水号码不能为空"}), 400

        logger.info(f"查询SMT1 AOI数据，流水号: {serial_number}")

        # 获取同批次所有流水号
        batch_serials = get_smt_npm_scan_record(serial_number)
        if not batch_serials:
            logger.warning(f"未找到流水号 {serial_number} 的批次信息")
            all_serials = [{"serialNumber": serial_number}]
        else:
            all_serials = batch_serials
            logger.info(f"同批次共有 {len(all_serials)} 个流水号")

        import glob

        # 遍历所有流水号查找文件
        for serial_data in all_serials:
            current_serial = serial_data["serialNumber"]
            logger.info(f"查找流水号 {current_serial} 的AOI文件")

            # 精确匹配流水号开头的文件
            pattern = os.path.join(SMT1_AOI_PATH, f"{current_serial}_*")
            matching_files = glob.glob(pattern)

            # 如果找到匹配文件，无论能否解析都立即处理并返回结果
            if matching_files:
                logger.info(f"找到匹配的文件: {matching_files[0]}")

                # 尝试解析第一个匹配的文件
                try:
                    file_path = matching_files[0]
                    file_content = read_file_with_multiple_encodings(file_path)

                    if file_content is None:
                        return jsonify({
                            "success": False,
                            "message": "找到文件但无法读取内容",
                            "files": [file_path],
                            "original_serial_number": serial_number
                        }), 404

                    parsed_data = detect_aoi_file_type(file_content, os.path.basename(file_path))
                    if parsed_data:
                        # 接受所有类型的AOI数据，不只是PARMI
                        unified_data = unify_aoi_data(parsed_data)
                        unified_data["serial_number"] = current_serial

                        return jsonify({
                            "success": True,
                            "data": [unified_data],
                            "file_path": file_path,
                            "device_type": parsed_data["device_type"],
                            "used_serial_number": current_serial,
                            "original_serial_number": serial_number
                        })
                    else:
                        return jsonify({
                            "success": False,
                            "message": "找到文件但无法解析数据",
                            "files": [file_path],
                            "original_serial_number": serial_number
                        }), 404

                except Exception as e:
                    logger.error(f"处理文件失败 {file_path}: {str(e)}")
                    return jsonify({
                        "success": False,
                        "message": f"文件处理失败: {str(e)}",
                        "files": [file_path],
                        "original_serial_number": serial_number
                    }), 404

        # 如果遍历完所有流水号仍未找到匹配文件
        return jsonify({
            "success": False,
            "message": f"未找到流水号 {serial_number} 及同批次产品的AOI数据文件",
            "original_serial_number": serial_number
        }), 404

    except Exception as e:
        logger.error(f"查询SMT1 AOI信息失败: {str(e)}")
        return jsonify({
            "success": False,
            "message": f"查询失败: {str(e)}"
        }), 500

